package com.ruoyi.archive.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.archive.mapper.ArchiveBuildingMapper;
import com.ruoyi.archive.domain.ArchiveBuilding;
import com.ruoyi.archive.service.IArchiveBuildingService;

import javax.validation.Validator;

/**
 * 楼栋信息Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-04-17
 */
@Service
public class ArchiveBuildingServiceImpl implements IArchiveBuildingService 
{
    private static final Logger log = LoggerFactory.getLogger(ArchiveBuildingServiceImpl.class);

    @Autowired
    private ArchiveBuildingMapper archiveBuildingMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    protected Validator validator;

    /**
     * 查询楼栋信息
     * 
     * @param id 楼栋信息主键
     * @return 楼栋信息
     */
    @Override
    public ArchiveBuilding selectArchiveBuildingById(Long id)
    {
        return archiveBuildingMapper.selectArchiveBuildingById(id);
    }

    /**
     * 查询楼栋信息列表
     * 
     * @param archiveBuilding 楼栋信息
     * @return 楼栋信息
     */
    @Override
    public List<ArchiveBuilding> selectArchiveBuildingList(ArchiveBuilding archiveBuilding)
    {
        return archiveBuildingMapper.selectArchiveBuildingList(archiveBuilding);
    }

    /**
     * 新增楼栋信息
     * 
     * @param archiveBuilding 楼栋信息
     * @return 结果
     */
    @Override
    public int insertArchiveBuilding(ArchiveBuilding archiveBuilding)
    {
        if(archiveBuilding.getCreateBy() == null){
            archiveBuilding.setCreateBy(SecurityUtils.getUsername());
        }
        archiveBuilding.setCreateTime(DateUtils.getNowDate());
        return archiveBuildingMapper.insertArchiveBuilding(archiveBuilding);
    }

    /**
     * 修改楼栋信息
     * 
     * @param archiveBuilding 楼栋信息
     * @return 结果
     */
    @Override
    public int updateArchiveBuilding(ArchiveBuilding archiveBuilding)
    {
        if(archiveBuilding.getUpdateBy() == null){
            archiveBuilding.setUpdateBy(SecurityUtils.getUsername());
        }
        archiveBuilding.setUpdateTime(DateUtils.getNowDate());
        return archiveBuildingMapper.updateArchiveBuilding(archiveBuilding);
    }

    /**
     * 批量删除楼栋信息
     * 
     * @param ids 需要删除的楼栋信息主键
     * @return 结果
     */
    @Override
    public int deleteArchiveBuildingByIds(Long[] ids)
    {
        return archiveBuildingMapper.deleteArchiveBuildingByIds(ids);
    }

    /**
     * 删除楼栋信息信息
     * 
     * @param id 楼栋信息主键
     * @return 结果
     */
    @Override
    public int deleteArchiveBuildingById(Long id)
    {
        return archiveBuildingMapper.deleteArchiveBuildingById(id);
    }

    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importData(List<ArchiveBuilding> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        SysDept dc = new SysDept();
        dc.setDelFlag("0");
        dc.setDeptType("community");;
        List<SysDept> deptList = sysDeptMapper.selectDeptList(dc);
        if(deptList == null || deptList.isEmpty()){
            throw new ServiceException("请先添加区域信息");
        }

        Map<String, Long> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptId));

        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        ArchiveBuilding bc = new ArchiveBuilding();
        for (ArchiveBuilding row : dataList)
        {
            try
            {
                if(StringUtils.isEmpty(row.getDeptName())){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、楼栋 " + row.getName() + " 的区域信息不能为空");
                    continue;
                }
                Long deptId = deptMap.get(row.getDeptName().trim());
                if(deptId == null){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、区域 " + row.getDeptName() + " 不存在");
                    continue;
                }
                row.setDeptId(deptId);
                BeanValidators.validateWithException(validator, row);

                bc.setDeptId(deptId);
                bc.setCode(row.getCode());

                // 验证是否存在旧数据
                List<ArchiveBuilding> old = archiveBuildingMapper.selectArchiveBuildingList(bc);
                if (StringUtils.isEmpty(old))
                {
                    row.setCreateBy(operName);
                    insertArchiveBuilding(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、楼栋 " + row.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setId(old.get(0).getId());
                    row.setUpdateBy(operName);
                    updateArchiveBuilding(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、楼栋 " + row.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、楼栋 " + row.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、楼栋 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
